package com.geek.video.web.controller;

import cn.hutool.core.util.RandomUtil;
import com.geek.video.enums.ResponseEnum;
import com.geek.video.service.UserInfoService;
import com.geek.video.service.dto.UserInfoDTO;
import com.geek.video.utils.JwtTokenUtil;
import com.geek.video.web.response.ResponseData;
import com.geek.video.web.vo.CommonVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;


/**
 * 用户表(UserInfo)表控制层
 *
 * @author qinxh
 * @since 2021-01-25 16:33:43
 */
@RestController
@RequestMapping("userInfo/")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @GetMapping("{id}/")
    public Mono<ResponseData> selectOne(@PathVariable("id") Integer id) {

        return ResponseData.ofSuccess(this.userInfoService.queryById(id));
    }

    @PostMapping("")
    public Mono<ResponseData> save(@RequestBody CommonVo commonVo) {

        if (ObjectUtils.isEmpty(commonVo) || StringUtils.isEmpty(commonVo.getImei())) {
            return ResponseData.ofStatus(ResponseEnum.BIND_ERROR);
        }
        UserInfoDTO userInfo = new UserInfoDTO();
        // ⽤户别名（随机⽣成）
        userInfo.setUserName(RandomUtil.randomString(10));
        // #6位随机数 (随机⽣成）
        userInfo.setUserCode("#" + RandomUtil.randomNumbers(6));
        // ⽤户头像 (随机⽣成）
        userInfo.setUsePhoto("" + RandomUtil.randomInt(1, 5) % 5);
        // 生成 token
        String token = jwtTokenUtil.generateToken(userInfo, commonVo.getImei());
        userInfo.setToken(token);
        userInfo.setCreateTime(System.currentTimeMillis());
        userInfo.setLastTime(userInfo.getCreateTime());

        return ResponseData.ofSuccess(userInfoService.insert(userInfo));
    }

}